package com.monbo.proj.lifangcrm.service.impl;

import com.monbo.proj.lifangcrm.entity.domain.HBizAttachment;
import com.monbo.proj.lifangcrm.entity.domain.I02tnAgreement;
import com.monbo.proj.lifangcrm.entity.domain.I02tnSheet1757915202701;
import com.monbo.proj.lifangcrm.mapper.HBizAttachmentMapper;
import com.monbo.proj.lifangcrm.mapper.I02tnAgreementMapper;
import com.monbo.proj.lifangcrm.mapper.I02tnSheet1757915202701Mapper;
import com.monbo.proj.lifangcrm.service.MinIOService;
import com.monbo.proj.lifangcrm.service.PdfCombinerService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fontbox.ttf.OTFParser;
import org.apache.fontbox.ttf.OpenTypeFont;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.util.Matrix;
import org.springframework.stereotype.Service;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * PDF合成服务Impl
 *
 * @author lirui
 * @date 2025/09/22
 */
@Slf4j
@Service
@AllArgsConstructor
public class PdfCombinerServiceImpl implements PdfCombinerService {

    private final MinIOService minIOService;
    private final I02tnAgreementMapper i02tnAgreementMapper;
    private final I02tnSheet1757915202701Mapper i02tnSheet1757915202701Mapper;
    private final HBizAttachmentMapper hBizAttachmentMapper;

    /**
     * 合成
     *
     * @param id id
     * @return {@link String }
     * @throws IOException ioexception
     */
    @Override
    public String combine(String id) throws IOException {

        log.info("开始生成PDF");
        // 获取客户协议表主表
        I02tnAgreement i02tnAgreementData = getI02tnAgreementData(id);

        // 获取产品明细子表数据
        List<I02tnSheet1757915202701> i02tnSheet1757915202701DataList = getI02tnSheet1757915202701DataByParentId(id);

        // 合成PDF
        ByteArrayOutputStream pdfOutputStream = createPdf(i02tnAgreementData, i02tnSheet1757915202701DataList);
        // 生成文件名
        String documentUuid = UUID.randomUUID().toString();
        String documentName = Instant.now().toString() + ".pdf";
        log.info("开始保存PDF,文档名称为:{}", documentName);
        // 上传文件
        InputStream inputStream = new ByteArrayInputStream(pdfOutputStream.toByteArray());
        log.info("开始上传PDF");
        String url = "";
        try {
            url = minIOService.pushOss(inputStream, documentUuid + documentName);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }

        log.info("PDF生成成功，文件名:{}，文件地址:{}", documentName, url);
        saveHBizAttachment(i02tnAgreementData, documentName, documentUuid, url, pdfOutputStream);

        return "生成成功";

    }


    /**
     * 获取I02tnAgreement数据
     *
     * @param id id
     * @return {@link I02tnAgreement }
     */
    public I02tnAgreement getI02tnAgreementData(String id) {
        log.debug("获取客户协议表主表数据，实例ID:{}", id);
        I02tnAgreement i02tnAgreementData = i02tnAgreementMapper.selectById(id);
        log.debug("获取客户协议表主表数据成功，数据:{}", i02tnAgreementData);
        return i02tnAgreementData;
    }

    /**
     * 根据父实例ID获取I02tnSheet1757915202701数据列表
     *
     * @param parentId 父id
     * @return {@link List }<{@link I02tnSheet1757915202701 }>
     */
    public List<I02tnSheet1757915202701> getI02tnSheet1757915202701DataByParentId(String parentId) {
        log.debug("获取客户协议表子表数据，实例ID:{}", parentId);
        List<I02tnSheet1757915202701> i02tnSheet1757915202701DataList = i02tnSheet1757915202701Mapper.selectByParentId(parentId);
        log.debug("获取客户协议表子表数据成功，数据:{}", i02tnSheet1757915202701DataList);
        return i02tnSheet1757915202701DataList;
    }

    /**
     * 创建pdf
     *
     * @param i02tnAgreementData              2万亿协议数据
     * @param i02tnSheet1757915202701DataList I02tn sheet1757915202701数据列表
     * @return {@link ByteArrayOutputStream }
     * @throws IOException ioexception
     */
    public ByteArrayOutputStream createPdf(I02tnAgreement i02tnAgreementData, List<I02tnSheet1757915202701> i02tnSheet1757915202701DataList) throws IOException {

        // 创建PDF文档
        PDDocument document = new PDDocument();
        // 创建页面
        PDPage page = new PDPage(PDRectangle.A4);
        // 添加页面
        document.addPage(page);

        // 设置页面边距和初始位置
        float margin = 50;
        float yPosition = PDRectangle.A4.getHeight() - margin;
        float lineHeight = 15;
        float tableRowHeight = 20;

        // 创建页面内容流
        PDPageContentStream pdPageContentStream = new PDPageContentStream(document, page);

        // 设置英文字体
        PDType1Font titleFont = PDType1Font.HELVETICA_BOLD;
        PDType1Font boldFont = PDType1Font.HELVETICA_BOLD;
        PDType1Font normalFont = PDType1Font.HELVETICA;

        PDRectangle mediaBox = page.getMediaBox();


        // 从classpath加载中文字体
        PDFont chineseFont = loadChineseFont(document);

        // 添加水印
        addWatermark(pdPageContentStream, page, "hjxz");


        // 标题 - 使用中文字体
        String title = "立方制药 OTC 终端合作协议";
        PDFont actualFont = chineseFont != null ? chineseFont : titleFont;
        float titleWidth = actualFont.getStringWidth(title) / 1000 * 16 * 1.5f;
        float startX = (mediaBox.getWidth() - titleWidth) / 2;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(actualFont, 16);
        pdPageContentStream.newLineAtOffset(startX, yPosition);
        pdPageContentStream.showText(title);
        pdPageContentStream.endText();
        yPosition -= lineHeight * 2;

        // 签订协议方 - 使用中文字体
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 12);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("签订协议方：");
        pdPageContentStream.endText();

        yPosition -= lineHeight * 2;
        pdPageContentStream.beginText();
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("甲方：合肥立方制药股份有限公司");
        pdPageContentStream.endText();
        yPosition -= lineHeight * 2;
        pdPageContentStream.beginText();
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("乙方：" + i02tnAgreementData.getShortText1758616897953());
        pdPageContentStream.endText();
        yPosition -= lineHeight * 2;

        // 协议正文 - 使用中英文字体

        // 拆分文本为多行
        float leading = 12 * 1.5f;
        String longText = "甲乙双方本着平等自愿的原则，为共同探索实践品牌产品广泛价值一体化及连锁药店运营多元化的新营销模式，经友好协商，达成如下战略合作协议：";
        List<String> lines = wrapText(longText, actualFont, 12, PDRectangle.A4.getHeight() - margin * 2);

        for (String line : lines) {
            pdPageContentStream.beginText();
            pdPageContentStream.setFont(actualFont, 12);
            pdPageContentStream.newLineAtOffset(margin, yPosition);
            pdPageContentStream.showText(line);
            pdPageContentStream.endText();
            yPosition -= leading;
        }

        // 开始时间
        Instant instantutcDataStart = Instant.parse(i02tnAgreementData.getDate1757913661091().toString());
        String startDate = DateTimeFormatter.ofPattern("yyyy年MM月dd日")
                .withZone(ZoneId.of("UTC"))
                .format(instantutcDataStart);


        //结束时间
        Instant instantutcDataSold = Instant.parse(i02tnAgreementData.getDate1757913669501().toString());
        String utcDateOld = DateTimeFormatter.ofPattern("yyyy年MM月dd日")
                .withZone(ZoneId.of("UTC"))
                .format(instantutcDataSold);


        yPosition -= lineHeight;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 12);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("第一部分  供货方式、合作期限、任务");
        pdPageContentStream.endText();
        yPosition -= lineHeight;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 12);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("1. 供货方式：乙方在甲方指定的供应商处进货，方能享受本协议政策。");
        pdPageContentStream.endText();
        yPosition -= lineHeight;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 12);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("指定商业：1. 华东医药有限公司;2. 国药控股安徽有限公司");
        pdPageContentStream.endText();
        yPosition -= lineHeight;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 12);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("2. 本协议履行期限自 " + startDate + " 至 " + utcDateOld + "。");
        pdPageContentStream.endText();
        yPosition -= lineHeight;



        long total = 0;
        for (I02tnSheet1757915202701 i02tnSheet1757915202701Data : i02tnSheet1757915202701DataList) {
            //产品名称
            String product = i02tnSheet1757915202701Data.getShortText1758618271507();
            // 规格
            String specification = i02tnSheet1757915202701Data.getDropdown1757915719381();
            // 第一季度
            long theFirstquarter = i02tnSheet1757915202701Data.getNumber1757915870860() + i02tnSheet1757915202701Data.getNumber1757915873532() + i02tnSheet1757915202701Data.getNumber1757915878198();
            // 第二季度
            long secondQuarter = i02tnSheet1757915202701Data.getNumber1757915881492() + i02tnSheet1757915202701Data.getNumber1757915885211() + i02tnSheet1757915202701Data.getNumber1757915896557();
            // 第三季度
            long thethirdQuarter = i02tnSheet1757915202701Data.getNumber1757915901573() + i02tnSheet1757915202701Data.getNumber1757915905665() + i02tnSheet1757915202701Data.getNumber1757915910265();
            // 第四季度
            long FourthQuarter = i02tnSheet1757915202701Data.getNumber1757915915093() + i02tnSheet1757915202701Data.getNumber1757915918585() + i02tnSheet1757915202701Data.getNumber1757915921897();
            // 总计金额
            long totalAmount = theFirstquarter + secondQuarter + thethirdQuarter + FourthQuarter;
            total = total + totalAmount;
        }

        // 3. 购进金额 - 使用中文字体
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 12);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("3. 乙方在协议期间，需从指定商业购进甲方产品共计" + total + "元，具体合作产品购进计划金额，如下表：");
        pdPageContentStream.endText();
        yPosition -= lineHeight * 2;

        // 绘制表格 - 表格内容使用中文字体
        float tableWidth = PDRectangle.A4.getWidth() - 2 * margin;
        float[] columnWidths = {100, 60, 70, 70, 70, 70, 70};
        drawTableRow(pdPageContentStream, margin, yPosition, tableWidth, tableRowHeight, columnWidths,
                new String[]{"产品名称", "规格", "1季度", "2季度", "3季度", "4季度", "合计金额"},
                chineseFont != null ? chineseFont : boldFont);
        yPosition -= tableRowHeight;

        for (I02tnSheet1757915202701 i02tnSheet1757915202701Data : i02tnSheet1757915202701DataList) {
            //产品名称
            String product = i02tnSheet1757915202701Data.getShortText1758618271507();
            // 规格
            String specification = i02tnSheet1757915202701Data.getDropdown1757915719381();
            // 第一季度
            long theFirstquarter = i02tnSheet1757915202701Data.getNumber1757915870860() + i02tnSheet1757915202701Data.getNumber1757915873532() + i02tnSheet1757915202701Data.getNumber1757915878198();
            // 第二季度
            long secondQuarter = i02tnSheet1757915202701Data.getNumber1757915881492() + i02tnSheet1757915202701Data.getNumber1757915885211() + i02tnSheet1757915202701Data.getNumber1757915896557();
            // 第三季度
            long thethirdQuarter = i02tnSheet1757915202701Data.getNumber1757915901573() + i02tnSheet1757915202701Data.getNumber1757915905665() + i02tnSheet1757915202701Data.getNumber1757915910265();
            // 第四季度
            long FourthQuarter = i02tnSheet1757915202701Data.getNumber1757915915093() + i02tnSheet1757915202701Data.getNumber1757915918585() + i02tnSheet1757915202701Data.getNumber1757915921897();
            drawTableRow(pdPageContentStream, margin, yPosition, tableWidth, tableRowHeight, columnWidths,
                    new String[]{product, specification, theFirstquarter + "", secondQuarter + "", thethirdQuarter + "", FourthQuarter + "", total + ""},
                    chineseFont != null ? chineseFont : normalFont);
            yPosition -= tableRowHeight;
        }
        yPosition -= tableRowHeight * 2;

        // 单位说明 - 使用中文字体
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 10);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("单位：元");
        pdPageContentStream.endText();
        yPosition -= lineHeight;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 10);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("第二部分  销售折扣以及日常维护要求");
        pdPageContentStream.endText();
        yPosition -= lineHeight;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 10);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("（一）销售折扣");
        pdPageContentStream.endText();
        yPosition -= lineHeight;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 10);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("1.甲方销售产品时，除按协议约定价格外，可获得以下折扣：");
        pdPageContentStream.endText();
        yPosition -= lineHeight;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 10);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("1. 乙方承诺不向所辖门店外渠道销售甲方产品，否则甲方有权取消销售折扣；");
        pdPageContentStream.endText();
        yPosition -= lineHeight;
        pdPageContentStream.beginText();
        pdPageContentStream.setFont(chineseFont != null ? chineseFont : normalFont, 10);
        pdPageContentStream.newLineAtOffset(margin, yPosition);
        pdPageContentStream.showText("2.以第一部分第3条约定的计划金额为准，乙方合计金额达成本 >80%时，甲方按下表给予乙方相应的销售折扣。销售折扣。");
        pdPageContentStream.endText();

        // 添加水印
        addSeal(pdPageContentStream, document, page, 40, (int) yPosition - 40);

        // 关闭流
        pdPageContentStream.close();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.save(outputStream);
        document.close();
        outputStream.close();

        return outputStream;
    }


    /**
     * 加载中文字体
     *
     * @param document 文档
     * @return {@link PDFont }
     */
    private PDFont loadChineseFont(PDDocument document) {
        PDFont chineseFont = null;
        try {
            // 尝试多种路径加载字体文件
            String[] fontPaths = {
                    "fonts/NotoSerifCJKsc-SemiBold.otf",
                    "/fonts/NotoSerifCJKsc-SemiBold.otf",
                    "NotoSerifCJKsc-SemiBold.otf"
            };

            InputStream inputStream = null;
            for (String fontPath : fontPaths) {
                inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fontPath);
                if (inputStream != null) {
                    break;
                }
            }

            if (inputStream != null) {
                OpenTypeFont otfFont = new OTFParser(false, true).parse(inputStream);
                chineseFont = PDType0Font.load(document, otfFont, false);
                log.info("中文字体加载成功");
            } else {
                log.warn("无法找到中文字体文件，将使用默认英文字体");
            }
        } catch (Exception e) {
            log.warn("中文字体加载失败，将使用默认英文字体: {}", e.getMessage());
        }
        return chineseFont;
    }

    /**
     * 添加水印
     *
     * @param contentStream 内容流
     * @param page          页面
     * @param watermarkText 水印文本
     * @throws IOException ioexception
     */
    private void addWatermark(PDPageContentStream contentStream, PDPage page, String watermarkText) throws IOException {
        // 设置水印字体和透明度
        contentStream.setFont(PDType1Font.HELVETICA, 48);
//        PDColor watermarkColor = new PDColor(new float[]{200, 200, 200}, PDDeviceRGB.INSTANCE);
        contentStream.setNonStrokingColor(200, 200, 200); // 浅灰色

        // 获取页面尺寸
        PDRectangle pageSize = page.getMediaBox();
        float pageWidth = pageSize.getWidth();
        float pageHeight = pageSize.getHeight();

        // 旋转45度并平铺水印
        contentStream.saveGraphicsState();
        for (int i = -2; i <= 2; i++) {
            for (int j = -2; j <= 2; j++) {
                contentStream.beginText();
                // 设置旋转矩阵
                Matrix matrix = Matrix.getRotateInstance(Math.toRadians(45),
                        pageWidth / 2 + i * 200, pageHeight / 2 + j * 150);
                contentStream.setTextMatrix(matrix);
                contentStream.showText(watermarkText);
                contentStream.endText();
            }
        }
        contentStream.restoreGraphicsState();

        // 重置颜色
        PDColor nonStrokingColor = new PDColor(new float[]{0, 0, 0}, PDDeviceRGB.INSTANCE);
        contentStream.setNonStrokingColor(nonStrokingColor);
    }

    /**
     * 绘制表行
     *
     * @param contentStream 内容流
     * @param x             x
     * @param y             y
     * @param tableWidth    表格宽度
     * @param rowHeight     行高
     * @param colWidths     坳宽度
     * @param values        值
     * @param font          字体
     * @throws IOException ioexception
     */
    private void drawTableRow(PDPageContentStream contentStream, float x, float y,
                              float tableWidth, float rowHeight, float[] colWidths,
                              String[] values, Object font) throws IOException {
        float currentX = x;

        // 绘制单元格边框和文本
        for (int i = 0; i < colWidths.length; i++) {
            // 绘制单元格边框
            contentStream.moveTo(currentX, y);
            contentStream.lineTo(currentX + colWidths[i], y);
            contentStream.lineTo(currentX + colWidths[i], y - rowHeight);
            contentStream.lineTo(currentX, y - rowHeight);
            contentStream.closePath();
            contentStream.stroke();

            // 添加文本
            if (values[i] != null) {
                contentStream.beginText();
                if (font instanceof PDType0Font) {
                    contentStream.setFont((PDType0Font) font, 10);
                } else if (font instanceof PDType1Font) {
                    contentStream.setFont((PDType1Font) font, 10);
                }
                contentStream.newLineAtOffset(currentX + 2, y - rowHeight / 2 - 4); // 居中文本
                contentStream.showText(values[i]);
                contentStream.endText();
            }

            currentX += colWidths[i];
        }
    }

    /**
     * 添加印章
     *
     * @param contentStream 内容流
     * @param document      文档
     * @param page          页面
     * @param xAxis         x轴
     * @param yAxis         y轴
     * @throws IOException ioexception
     */
    private void addSeal(PDPageContentStream contentStream, PDDocument document, PDPage page, int xAxis, int yAxis) throws IOException {
        try {
            // 尝试加载印章图片
            InputStream sealStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("images/seal.png");

            if (sealStream != null) {
                PDImageXObject sealImage = PDImageXObject.createFromByteArray(document,
                        sealStream.readAllBytes(), "seal");

                // 在页面右下角添加印章
                float sealWidth = 120;
                float sealHeight = 120;
                float x = page.getMediaBox().getWidth() - sealWidth - xAxis; // 右边距50
                // 底部位置

                contentStream.drawImage(sealImage, x, (float) yAxis, sealWidth, sealHeight);
                log.info("印章添加成功");
            } else {
                // 如果没有印章图片，绘制一个简单的圆形印章
                log.warn("无法加载印章图片，绘制简单印章");
            }
        } catch (Exception e) {
            log.warn("无法加载印章图片，绘制简单印章", e);
        }
    }


    public void saveHBizAttachment(I02tnAgreement i02tnAgreementData, String documentName, String documentUuid, String url, ByteArrayOutputStream pdfOutputStream) {
        HBizAttachment hBizAttachment = new HBizAttachment();
        hBizAttachment.setBizObjectId(i02tnAgreementData.getId());
        hBizAttachment.setBizPropertyCode("Attachment1758543395364");
        hBizAttachment.setCreater(i02tnAgreementData.getCreater());
        hBizAttachment.setCreatedTime(Instant.now());
        hBizAttachment.setFileExtension(".pdf");
        hBizAttachment.setFileSize(pdfOutputStream.size());
        hBizAttachment.setMimeType("application/pdf");
        hBizAttachment.setName(documentName);
        hBizAttachment.setRefId(documentUuid + documentName);
        hBizAttachment.setSchemaCode("agreement");
        hBizAttachment.setSortKey(0);
        hBizAttachmentMapper.insert(hBizAttachment);
    }

    /**
     * 支持中文的文本自动换行算法
     * 处理逻辑：逐个字符添加并判断宽度，遇到标点符号优先换行
     *
     * @param text     要处理的文本（可包含中文、英文、数字等）
     * @param font     字体（需支持中文）
     * @param fontSize 字体大小
     * @param maxWidth 最大允许宽度
     * @return 拆分后的文本行列表
     * @throws IOException 字体处理异常
     */
    private static List<String> wrapText(String text, PDFont font, float fontSize, float maxWidth) throws IOException {
        List<String> lines = new ArrayList<>();
        if (text == null || text.isEmpty()) {
            return lines;
        }

        StringBuilder currentLine = new StringBuilder();

        // 逐个字符处理（支持中文）
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            // 尝试添加当前字符
            String temp = currentLine.toString() + c;

            // 计算临时文本宽度
            float width = font.getStringWidth(temp) / 1000 * fontSize * 1.5f;

            // 如果超过最大宽度，进行换行处理
            if (width > maxWidth) {
                // 当前行不为空时，添加到列表
                if (currentLine.length() > 0) {
                    lines.add(currentLine.toString());
                    currentLine = new StringBuilder(String.valueOf(c));
                } else {
                    // 单个字符就超过宽度（极少情况），直接添加
                    lines.add(String.valueOf(c));
                    currentLine = new StringBuilder();
                }
            } else {
                currentLine.append(c);
            }
        }

        // 添加最后一行
        if (currentLine.length() > 0) {
            lines.add(currentLine.toString());
        }

        return lines;
    }






}
